package pl.edu.agh.io.fx3.saver.generators;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.postgresql.util.PSQLException;

import pl.edu.agh.io.fx3.utils.JDBCInfo;

public class PostgreSQLSchemaGenerator implements ISchemaGenerator {

	public void generate(JDBCInfo info) throws SQLException {
		Properties props = new Properties();
		props.setProperty("user", info.getUsername());
		props.setProperty("password", info.getPassword());
		Connection conn = DriverManager.getConnection(info.getUrl(), props);
		
		try {
			conn.createStatement().executeQuery("DROP TABLE files;\n");
		} catch (PSQLException e) {
			System.err.println(e.getLocalizedMessage());
		}
		
		try {
			conn.createStatement().executeQuery("DROP SCHEMA public CASCADE;\n");
		} catch (PSQLException e) {
			System.err.println(e.getLocalizedMessage());
		}
		
		try {
			conn.createStatement().executeQuery("CREATE SCHEMA public;\n" +
					"CREATE SEQUENCE files_id_seq INCREMENT BY 1;\n" +
					"CREATE TABLE files\n" +
					"(\n" +
					"id BIGINT NOT NULL DEFAULT nextval('files_id_seq'),\n" +
					"virtual_path VARCHAR(1024) UNIQUE NOT NULL,\n" +
					"real_path VARCHAR(1024) UNIQUE NOT NULL,\n" +
					"checksum VARCHAR(255) NOT NULL\n" +
					");\n" +
					"ALTER TABLE files ADD CONSTRAINT pkfiles\n" +
					"PRIMARY KEY (id);\n");
		} catch (PSQLException e) {
			System.err.println(e.getLocalizedMessage());
		} finally {
			conn.close();
		}
		
		
	}
}
